package com.eqdd.yiqidian.ui.mine

import android.content.Intent
import android.net.Uri
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.AppConstent
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.EnterBean
import com.eqdd.yiqidian.bean.SelectBean
import com.eqdd.yiqidian.bean.rebuild.*
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.bottomCustomDialog
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.rongyun.message.mingpian.Content
import com.eqdd.yiqidian.rongyun.message.mingpian.MingpianMessage
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.ui.discover.workcircle.PersonWorkCircleActivity
import com.eqdd.yiqidian.ui.mine.maker.OwnerMakerSpaceActivity
import com.eqdd.yiqidian.ui.mine.space.OwnerComSpaceActivity
import com.eqdd.yiqidian.ui.share.ShareEnterActivity
import com.eqdd.yiqidian.utils.IMUtil
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.ToastUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCSwipeRefreshHelper
import io.reactivex.Flowable
import io.rong.imkit.RongIM
import io.rong.imlib.IRongCallback
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import kotlinx.android.synthetic.main.activity_title.*
import kotlinx.android.synthetic.main.activity_user_card.*
import kotlinx.android.synthetic.main.list_item_189.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

class UserCardActivity : BaseActivity() {
    private var slimAdapterEx: SlimAdapterEx<*>? = null
    private var guid: String? = null
    private var datas: ArrayList<Any>? = null
    private var name: String? = null
    private var items: UserCardInfoResultBean? = null

    override fun initBinding() {
        setContentView(R.layout.activity_user_card)
        initTopTitleBar(View.VISIBLE, "个人名片")
        iv_right.setImageResource(R.mipmap.addg)
        iv_right.visibility = View.VISIBLE
        popMenu(arrayListOf("工作圈权限", "修改备注", "发名片", "删除"), iv_right) { dialog, pos ->
            when (pos) {
                0 -> {
                    startActivity<FriendCircleSettingActivity>("friendGuid" to guid)
                }
                1 -> {
                    startActivityForResult<EditTextActivity>(100, "content" to items?.upname, "title" to "备注", "tip" to "备注")
                }
                2 -> {
                    val shareConf = ShareConf().setTitle("请选择")
                            .setRightTitle("发送")
                            .setMaxNum(5)
                            .setMaxTip("最多%d人")

                    val shareEnterConf = ShareEnterConf()
                            .setFriendConf(shareConf)
                            .setQunChooseConf(shareConf)
                            .setQunListConf(shareConf)
                            .setQunMemberConf(shareConf)
                            .setStaffConf(shareConf)
                            .setShare(false)
                            .setAll(false)
                            .setTitle("请选择")
                            .setMaxNum(5)
                            .setRightTitle("发送")
                            .setMaxTip("最多%d人") as ShareEnterConf
                    startActivityForResult<ShareEnterActivity>(Config.SHARE_ENTER, "bean" to shareEnterConf)
                }
                3 -> delete()
            }

        }
        tv_addCRM.onClick {
            addCRM()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (requestCode == Config.SHARE_ENTER) {
            if (resultCode == Config.SUCCESS) {
                val selectBeans = data.getParcelableArrayListExtra<SelectBean>(Config.SELECTED_BEANS)
                for (selectBean in selectBeans) {
                    if (selectBean.type == Conversation.ConversationType.PRIVATE) {
                        val content = Content(items?.uname, items?.photo,
                                items?.department, items?.post,
                                items?.company, items?.userGuid, "0")

                        val obtain = MingpianMessage.obtain(content)
                        val message = Message.obtain(selectBean.guid, selectBean.type, obtain)
                        RongIM.getInstance().sendMessage(message, null, null, object : IRongCallback.ISendMessageCallback {
                            override fun onAttached(message: Message) {

                            }

                            override fun onSuccess(message: Message) {
                                println("发送成功")
                            }

                            override fun onError(message: Message, errorCode: RongIMClient.ErrorCode) {
                                println(errorCode.toString())
                            }

                        })
                    }
                }
            }
        }

        if (requestCode == 100 && resultCode == Config.INTENT_CONTENT) {
            val content = data.getStringExtra("content")
            if (content != null && "" != content) {
                OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.CHANGE_REMARK)
                        .params("userGuid", AppConstent.user.guid)
                        .params("friendGuid", guid)
                        .params("remarks", content)
                        .execute(object : DialogCallBack<HttpResult<*>>(this@UserCardActivity) {
                            override fun onSuccess(response: Response<HttpResult<*>>) {
                                val httpResult = response.body()
                                ToastUtil.showShort(httpResult.msg)
                                if (httpResult.status == 200) {
                                    setView()
                                }
                            }
                        })
            }

        }
    }

    private fun delete() {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.FRIEND_DELETE)
                .params("userGuid", AppConstent.user.guid)
                .params("friendGuid", guid)
                .execute(object : DialogCallBack<HttpResult<*>>(this@UserCardActivity) {
                    override fun onSuccess(response: Response<HttpResult<*>>) {
                        val httpResult = response.body()
                        ToastUtil.showShort(httpResult.msg)
                        if (httpResult.status == 200) {
                            finish()
                        }
                    }
                })
    }

    override fun initData() {
        datas = ArrayList()
        val list = arrayListOf<Any>()
        guid = intent.getStringExtra(Config.GUID)
        recyclerView.layoutManager = LinearLayoutManager(this)
        slimAdapterEx = SlimAdapterEx.create()
                .register<SlimEditHintBean>(R.layout.list_item_39, SlimInjector<SlimEditHintBean> { data, injector ->
                    if (data?.title === "手机号") {
                        injector?.clicked(R.id.tv_right) { v ->
                            val intent = Intent(Intent.ACTION_DIAL)
                            val url = Uri.parse("tel:" + data?.content)
                            intent.data = url
                            startActivity(intent)
                        }
                    }
                    injector?.text(R.id.tv_left, data?.title)
                            ?.text(R.id.tv_right, data?.content)
                })
                .register<Int>(R.layout.list_item_32, SlimInjector<Int> { data, injector -> }).register<EnterBean>(R.layout.list_item_134, SlimInjector<EnterBean> { data, injector ->
                    injector?.text(R.id.tv_title, data?.content)
                            ?.clicked(R.id.tv_title) { view ->
                                if ("企业空间" == data?.content) {
                                    startActivity<OwnerComSpaceActivity>(Config.COMPANY_ID to items?.companyId)
                                } else if ("个人工作圈" == data?.content) {
                                    startActivity<PersonWorkCircleActivity>(Config.ID to guid)
                                } else if ("创客空间" == data?.content) {
                                    startActivity<OwnerMakerSpaceActivity>(Config.GUID to guid, Config.COMPANY_ID to items?.companyId,
                                            "avatar" to items?.photo, "name" to items?.upname)
                                }
                            }
                })
                .register<String>(R.layout.list_item_40, SlimInjector<String> { data, injector ->
                    injector?.text(R.id.tv_center, data)
                }).attachTo(recyclerView).updateData(list as List<*>?)
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    if (slimAdapterEx?.getDataItem(position) is String) {
                        if ("发消息" == slimAdapterEx?.getDataItem(position)) {
                            IMUtil.startPrivate(this@UserCardActivity, guid, name, items?.photo)
                        } else if ("加好友" == slimAdapterEx?.getDataItem(position)) {
                            addFriend()
                        }
                    }
                }


    }

    private fun addFriend() {
        val editText = EditText(this)
        editText.setHintTextColor(resources.getColor(R.color.hint_color))
        editText.hint = "请输入验证信息"
        AlertDialog.Builder(this)
                .setTitle("发送好友请求")
                .setView(editText)
                .setPositiveButton("确定") { d, i ->
                    d.dismiss()
                    OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.INVITE_FRIEND)
                            .params("userid", user.guid)
                            .params("friendid", guid)
                            .params("addcontent", if (TextUtils.isEmpty(editText.text)) "" else editText.text.toString())
                            .execute(object : DialogCallBack<HttpResult<*>>(this@UserCardActivity) {
                                override fun onSuccess(response: Response<HttpResult<*>>) {
                                    val result = response.body()
                                    if (result.status == 200) {
                                        ToastUtil.showShort("请求成功")
                                    }
                                }
                            })

                }
                .setNegativeButton("取消") { d, i -> d.dismiss() }.show()
    }

    override fun setView() {
        OkGo.post<HttpResult<UserCardInfoResultBean>>(HttpConfig.BASE_URL + HttpConfig.USER_CARD_INFO)
                .params("userGuid", guid)
                .params("myGuid", AppConstent.user.guid)
                .execute(object : DialogCallBack<HttpResult<UserCardInfoResultBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<UserCardInfoResultBean>>) {
                        val httpResult = response.body()
                        if (httpResult.status == 200) {
                            items = httpResult.items
                            datas?.clear()
                            datas?.add(50)
                            datas?.add(SlimEditHintBean("手机号", items?.uname, 1))
                            datas?.add(SlimEditHintBean("地区", items?.location, 1))
                            datas?.add(EnterBean("个人工作圈"))
                            datas?.add(EnterBean("创客空间"))
                            datas?.add(EnterBean("企业空间"))
                            datas?.add(50)
                            datas?.add(SlimEditHintBean("公司", items?.company, 1))
                            datas?.add(SlimEditHintBean("部门职位", items?.department + "/" + items?.post, 1))
                            datas?.add(50)
                            datas?.add("发消息")
                            isFriend()
                            ImageUtil.setCircleImage(items?.photo, iv_head)
                            tv_top.text = items?.upname
                            name = items?.upname
                            tv_down.text = "易企点号：" + if (TextUtils.isEmpty(items?.eqdCode)) "暂无" else items?.eqdCode
                        } else {
                            finish()
                        }
                    }
                })

    }

    private fun isFriend() {
        OkGo.post<HttpResult<Int>>(HttpConfig.BASE_URL + HttpConfig.IS_FRIEND)
                .params("userGuid", guid)
                .params("myGuid", AppConstent.user.guid)
                .execute(object : DialogCallBack<HttpResult<Int>>(this) {
                    override fun onSuccess(response: Response<HttpResult<Int>>) {
                        val result = response.body()
                        if (result.status == 200) {
                            if (result.items != 11 && result.items != 1) {
                                datas?.add("加好友")
                                datas?.remove("发消息")
                                slimAdapterEx?.updateData((datas as List<Nothing>?))
                            } else {
                                slimAdapterEx?.updateData((datas as List<Nothing>?))
                            }
                        }
                    }
                })
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.iv_erweima -> {
                startActivity<UserErweimaActivity>(Config.GUID to guid, Config.NAME to name)
            }
        }
    }

    fun addCRM() {
        bottomCustomDialog(R.layout.list_item_189) { v, dialog ->
            var pageNum = 0
            val list = arrayListOf<ClientListResultBean>()
            val mvcHelper = MVCSwipeRefreshHelper<List<ClientListResultBean>>(v.swipeRefresh)
            v.swipeRefresh.setProgressViewEndTarget(true, 0)
            v.recyclerView.layoutManager = LinearLayoutManager(this)
            v.recyclerView.addItemDecoration(DividerLineItemDecoration(this).setFirstDraw(true))
            val slimAdapterEx = SlimAdapterEx.create()
                    .register<ClientListResultBean>(R.layout.list_item_190, SlimInjector<ClientListResultBean> { data, injector ->
                        injector?.text(R.id.tv_content, data?.cusName)
                                ?.text(R.id.tv_position, data?.salesTerritory)
                    })
                    .attachTo(v.recyclerView)
                    .updateData(list as List<ClientListResultBean>?) as SlimAdapterEx<ClientListResultBean>
            ItemClickSupport.addTo(v.recyclerView)
                    .setOnItemClickListener { recyclerView, position, v ->
                        dialog.dismiss()
                        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.KEHU_ADD_LIANXIREN)
                                .params("name", items?.username)
                                .params("owner", user.guid)
                                .params("dep", items?.department)
                                .params("post", items?.post)
                                .params("cellphone", items?.uname)
                                .params("conqq", items?.qq)
                                .params("conwx", items?.weChat)
                                .params("email", items?.email)
                                .params("remark", items?.signature)
                                .params("cusid", slimAdapterEx.getDataItem(position).id)
                                .execute(object : DialogCallBack<HttpResult<*>>(this@UserCardActivity) {
                                    override fun onSuccess(response: Response<HttpResult<*>>) {
                                        val httpResult = response.body()
                                        if (httpResult.status == 200) {
                                            toast("添加成功")
                                        } else {
                                            toast(httpResult.msg)
                                        }
                                    }
                                })
                    }
            val dataSource = ModelRx2DataSource<ClientListResultBean>(ModelRx2DataSource.OnLoadSource<ClientListResultBean> { page, register ->
                OkGo.post<ZhangPageResultBean<List<ClientListResultBean>>>(HttpConfig.BASE_URL + HttpConfig.KEHU_LIST)
                        .params("page", pageNum)
                        .params("owner", user.guid)
                        .converter(object : JsonConverter<ZhangPageResultBean<List<ClientListResultBean>>>() {
                            override fun test() {
                                super.test()
                            }
                        })
                        .adapt(FlowableBody<ZhangPageResultBean<List<ClientListResultBean>>>())
                        .flatMap({ result ->
                            if (page == 1) {
                                mvcHelper.isAutoLoadMore = true
                            }
                            pageNum = result.getNextpage()
                            Flowable.just(result.items ?: arrayListOf())
                        })


            }, 10)
            mvcHelper.setDataSource(dataSource)
            mvcHelper.adapter = slimAdapterEx
            mvcHelper.refresh()


        }
    }
}
